package com.murphy.base.interceptor;

import com.murphy.system.model.User;
import com.murphy.utils.LoginAttribute;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器
 * @author chenhy
 *
 * 2013-1-10 下午5:00:48
 */
public class LoginSessionInterceptor implements HandlerInterceptor {
	private static Logger logger = LoggerFactory.getLogger(LoginSessionInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

		// 加载拦截器排除地址
		String path = new LoginSessionInterceptor().getClass().getClassLoader().getResource("/").getPath() + "\\sys\\auth-exclude.xml";
		path = com.murphy.utils.StringUtils.getRootPath(path);
        PathFilter pt = new PathFilter();
		pt.setPath(path);
		
		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpReq.getSession();
		boolean flag = false;
		////iframe引起的内部cookie丢失
		httpResponse.setHeader("P3P", "CP=CAO PSA OUR");
		
		String method = httpReq.getMethod();
		String reqPath = "";
		if (method.equals("GET") || method.equals("POST")) {
			reqPath = extractRequestPath(httpReq);
			if (pt.isPathExclude(reqPath)) {
				flag = true;
//				打印非拦截地址
                logger.info(reqPath + " is exclude");
			} else {
				String loginName = (String) session.getAttribute(LoginAttribute.SESSION_LOGIN_NAME);
				if (StringUtils.isBlank(loginName)) {
					Cookie cookie = getCookieByName(httpReq, LoginAttribute.SESSION_LOGIN_NAME);
					if (null != cookie) {
						//
						loginName = cookie.getValue();
						loginName = setSessionLoginParam(httpReq, loginName);
					}
				}
				if (StringUtils.isNotBlank(loginName)) {
					flag = true;
				}
			}
		} else {
			flag = true;
		}
		
		if (!flag) {
			logger.info("session invalidate!login first!, request path: " + reqPath);
			response.sendRedirect(httpReq.getContextPath() + "/mup-login.jsp");
			
			return false;
		} else {
			return true;
		}
	}
	
	private String extractRequestPath(HttpServletRequest request) {
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		String query = request.getQueryString();
		
		return (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo)
				+ (query == null ? "" : ("?" + query));
	}

	private Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> map = readCookieMap(request);
		if (map.containsKey(name)) {
			return map.get(name);
		} else {
			return null;
		}
	}

	private Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}

	private String setSessionLoginParam(HttpServletRequest request, String loginName) {
//		UserService userService = SpringContextHolder.getBean("userService");
//		User user = userService.getUserByLoginName(loginName, false, true);
		User user = new User();
		if (user != null) {
//			int status = user.getStatus();
//			if (status == User.STATUS_NORMAL) {
//				HttpSession session = request.getSession();
//
//				session.setAttribute(LoginAttribute.SESSION_USER_ID, user.getId());
//				session.setAttribute(LoginAttribute.SESSION_LOGIN_NAME, user.getLoginName());
//				session.setAttribute(LoginAttribute.SESSION_USER_NAME, user.getName());
//
//				if (!loginName.equals("admin")) {
//					session.setAttribute(LoginAttribute.SESSION_DEPT_TITLE, user.getMainDept().getName());
//					session.setAttribute(LoginAttribute.SESSION_DEPT_ALIAS, user.getMainDept().getAlias());
//				}
//			}
		} else {
			loginName = null;
		}

		return loginName;
	}

}
